package com.zhongde.cloud89app.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

import com.android.tu.loadingdialog.LoadingDailog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.zhongde.cloud89app.R;
import com.zhongde.cloud89app.activity.DataInfoActivity;
import com.zhongde.cloud89app.activity.SetActivity;
import com.zhongde.cloud89app.adapter.EquipmentsAdapter;
import com.zhongde.cloud89app.bean.Equipment;
import com.zhongde.cloud89app.utils.MyPreference;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

import static com.zhongde.cloud89app.base.Configuration.BASE_URL;


/**
 *
 */
public class HomeFragment extends Fragment {

    private SwipeRefreshLayout swipeRefreshLayout;
    private Context context;
    private List<Equipment> equipments = new ArrayList<Equipment>();
    private EquipmentsAdapter adapter;
    private RecyclerView recyclerView;
    private FloatingActionButton add_equipment;
    private MyPreference pref;
    private LoadingDailog dialog;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_home, null);
        recyclerView = view.findViewById(R.id.equipments_list);
        add_equipment = view.findViewById(R.id.add_equipment);

        swipeRefreshLayout = view.findViewById(R.id.home_swipeRefreshLayout);

        //初始化等待对话框
        LoadingDailog.Builder loadBuilder = new LoadingDailog.Builder(context)
                .setMessage("正在设置中...")
                .setCancelable(false)
                .setCancelOutside(false);
        dialog = loadBuilder.create();

        initRecyclerView();
        setOnclick();
        return view;

    }

    private void setOnclick() {
        add_equipment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("添加设备");        //设置弹出窗口的标题
                View view = LayoutInflater.from(context).inflate(R.layout.add_equipment_dialog, null);
                final EditText eid = view.findViewById(R.id.dt_equipment_id);
                final EditText epwd = view.findViewById(R.id.dt_equipment_pwd);
                builder.setView(view);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    //设定PositiveButton
                    @Override
                    public void onClick(DialogInterface dialog, int which) {


                        String seid = eid.getText().toString();
                        String spwd = epwd.getText().toString();

                        if (seid.trim().length() == 0 || spwd.trim().length() == 0) {
                            Toast.makeText(context, "请输完整信息", Toast.LENGTH_SHORT).show();
                            return;
                        }


                        AddMenuname(seid, spwd);
                    }
                });
                builder.show();
            }
        });

        swipeRefreshLayout.setOnRefreshListener(() -> {

            initData();

        });

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        pref = new MyPreference(context);
        if (pref.getInt("userleve") == 2) {
            add_equipment.setVisibility(View.GONE);
        }
        initData();

    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {


        OkHttpUtils
                .post()
                .url(BASE_URL + "AppcallingInterface_Controller/Menu_Information.do")
                .addParams("username", pref.getString("userName"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        equipments.clear();
                        try {
                            JSONArray jsonArray = new JSONArray(response);
                            if (jsonArray.length() > 0) {


                                for (int i = 0; i < jsonArray.length(); i++) {
                                    Equipment equipment = new Equipment();
                                    equipment.setEquipmentId(jsonArray.getJSONObject(i).getString("menuname"));
                                    equipment.setAreaName(jsonArray.getJSONObject(i).getString("areaName"));
                                    equipment.setCondit(jsonArray.getJSONObject(i).getInt("condit"));
                                    equipment.setTask_status(jsonArray.getJSONObject(i).getInt("taskStatus"));
                                    equipment.setWheelAll(jsonArray.getJSONObject(i).getString("wheelAll"));
                                    equipment.setAreaNumber(jsonArray.getJSONObject(i).getString("areaNumber"));

                                    equipments.add(equipment);
                                }
                                if (swipeRefreshLayout.isRefreshing()) {
                                    swipeRefreshLayout.setRefreshing(false);
                                }
                                adapter.notifyDataSetChanged();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

    }


    private void AddMenuname(String menuname, String menunamePassword) {
        OkHttpUtils
                .post()
                .url(BASE_URL + "Z_d_menuname_msg_Controller/AddMenuname.do")
                .addParams("username", pref.getString("userName"))
                .addParams("menuname", menuname)
                .addParams("menunamePassword", menunamePassword)

                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            Toast.makeText(context, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                            if (jsonObject.getInt("code") == 1) initData();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void initRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        adapter = new EquipmentsAdapter(R.layout.equipment_item, equipments, context);
        recyclerView.setAdapter(adapter);
        adapter.getData().clear();
        adapter.setEmptyView(R.layout.empty_view);
        adapter.notifyDataSetChanged();

        View view = LayoutInflater.from(getContext()).inflate(R.layout.footer_layout, null);
        adapter.setFooterView(view);
        adapter.addChildClickViewIds(R.id.item_settings_equipment);
        adapter.addChildClickViewIds(R.id.eq_restart);
        adapter.addChildClickViewIds(R.id.eq_start);
        adapter.addChildClickViewIds(R.id.eq_stop);
        adapter.addChildClickViewIds(R.id.eq_finish);

//        View view = LayoutInflater.from(getContext()).inflate(R.layout.footer_layout, null);
//        adapter.addFooterView(view);
        adapter.setOnItemChildClickListener((adapter, view1, position) -> {

            if (view1.getId() == R.id.item_settings_equipment) {

//                AlertDialog.Builder builder = new AlertDialog.Builder(context);
//                builder.setTitle("警告");        //设置弹出窗口的标题
//                builder.setMessage("是否确定解除设备绑定？");
//                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    //设定PositiveButton
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                        removeEquipment(equipments.get(position).getEquipmentId());
//                    }
//                });
//                builder.setNeutralButton("取消", null);
//                builder.show();

                Intent intent = new Intent(context, SetActivity.class);
                intent.putExtra("menuname", equipments.get(position).getEquipmentId());
                context.startActivity(intent);


            }
            if (view1.getId() == R.id.eq_restart) {
                showDialog("是否确定重启？", position, 1);
            }
            if (view1.getId() == R.id.eq_start) {
                showDialog("是否确定启动？", position, 2);
            }
            if (view1.getId() == R.id.eq_stop) {
                showDialog("是否确定暂停？", position, 3);
            }
            if (view1.getId() == R.id.eq_finish) {
                showDialog("是否确定停止？", position, 4);
            }


        });


        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                Intent intent = new Intent(context, DataInfoActivity.class);
                intent.putExtra("menuname", equipments.get(position).getEquipmentId());
                startActivity(intent);

            }
        });

    }

    private void showDialog(String msg, int position, int flag) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("警告");
        String url = "";
        switch (flag) {
            case 1:
                builder.setTitle("重启");
                builder.setIcon(R.drawable.ic_action_restart);
                url = "AppAndMenuExchange_Controller/Equipment_Restart.do";
                break;
            case 2:
                if (equipments.get(position).getTask_status() == 3) {
                    builder.setTitle("继续");
                    builder.setIcon(R.drawable.ic_action_play);
                    url = "AppAndMenuExchange_Controller/continue_meter_reading.do";
                } else {
                    builder.setTitle("启动");
                    builder.setIcon(R.drawable.ic_action_play);
                    url = "AppAndMenuExchange_Controller/Device_Start_Task.do";
                }
                break;
            case 3:
                builder.setTitle("暂停");
                builder.setIcon(R.drawable.ic_action_pause);
                url = "AppAndMenuExchange_Controller/Suspension_meter_reading.do";
                break;
            case 4:
                builder.setTitle("停止");
                builder.setIcon(R.drawable.ic_action_stop);
                url = "AppAndMenuExchange_Controller/End_Of_Task.do";
                break;
        }
        //设置弹出窗口的标题
        builder.setMessage(msg);
        String finalUrl = url;
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            //设定PositiveButton
            @Override
            public void onClick(DialogInterface dialogs, int which) {
                dialog.show();
                OkHttpUtils
                        .post()
                        .url(BASE_URL + finalUrl)
                        .addParams("menuname", equipments.get(position).getEquipmentId())
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    Toast.makeText(context, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                                    if (jsonObject.getInt("code") == 1) {
                                        initData();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onAfter(int id) {
                                super.onAfter(id);
                                dialog.dismiss();
                            }
                        });

            }
        });
        builder.setNeutralButton("取消", null);
        builder.show();
    }

    private void removeEquipment(String equipmentId) {
        OkHttpUtils
                .post()
                .url(BASE_URL + "Z_d_menuname_msg_Controller/deleteMenuname.do")
                .addParams("username", pref.getString("userName"))
                .addParams("menuname", equipmentId)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.getInt("code") == 1) {
                                Toast.makeText(context, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                                initData();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


}